package com.itheima.dao;

import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class FakeDao {

    @Autowired
    private RestTemplate restTemplate;

    private static Logger logger = LoggerFactory.getLogger(FakeDao.class);

    @HystrixCommand(fallbackMethod = "queryUserByIdFallback")
    public User queryUserById(Long id) {
        Long start = System.currentTimeMillis();
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();

        String baseUrl = "http://user-service/user/hello/";

        User user = restTemplate.getForObject(baseUrl + id, User.class);


//        ids.forEach(id -> list.add(restTemplate.getForObject(baseUrl + id,User.class)));

//        ids.forEach(id -> list.add(restTemplate.getForObject("http://localhost:8081/user/hello/" + id,User.class)));

        Long end = System.currentTimeMillis();

        Long time = end - start;

        logger.info("本次查询：{}，访问用时：{}ms",id,time);
        return user;
    }

    public User queryUserByIdFallback(Long id){
        User user = new User();
        user.setId(id);
        user.setName("用户信息查询出现异常！");
        return user;
    }
}
